/****************************************************
	文件：RoutineHandle.cs
	作者：HuskyT
	邮箱：1005240602@qq.com
	日期：2021/1/2 14:28:56
	功能：协程处理器
*****************************************************/

using System.Collections;

namespace HTFW.Core
{
    public class RoutineHandle : IRoutineHandle
    {
        IEnumerator mSelfRoutine;
        RoutineState mState;

        public IEnumerator SelfRoutine => mSelfRoutine;
        public RoutineState State => mState;

        public int ObjectPoolIndex { get; set; }

        public bool HasInit { get; private set; }

        public void Init(IEnumerator routine, bool autoStartNow = true)
        {
            mSelfRoutine = routine;

            if (autoStartNow)
                mState = RoutineState.Running;
            else
                mState = RoutineState.Waiting;

            HasInit = true;
        }

        /// <summary>
        /// 销毁协程（框架内部调用，不对外使用，如需关闭协程使用 Stop()）
        /// </summary>
        public void Dispose()
        {
            if (!HasInit) return;

            if (mState == RoutineState.Running)
                Stop();

            mSelfRoutine = null;
            HasInit = false;
        }

        /// <summary>
        /// 开启协程
        /// </summary>
        public void Start()
        {
            if (!HasInit) return;

            if (mState == RoutineState.Waiting)
            {
                mState = RoutineState.Running;
                CoroutineService.Instance.StartCoroutine(this);
            }
        }

        /// <summary>
        /// 关闭协程
        /// </summary>
        public void Stop()
        {
            if (!HasInit) return;

            if (mState == RoutineState.Running)
            {
                mState = RoutineState.Stop;
                CoroutineService.Instance.StopCoroutine(this);
            }
        }
    }
}